﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplicationTest
{
    public partial class RSA : System.Web.UI.Page
    {
        String strData = "";
        String appId = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //Label1.Text = Request.QueryString["param"];
            //Label1.Text = Request.Params.Get("HTTP_HOST");

            Label1.Text = Request.Url.ToString();

            strData = Request.QueryString["strData"];
            appId = Request.QueryString["appId"]; ;

            String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAs0SfSS4GOQoxf3irkSSBhPy9cpUs5cO3YUi2T65Gt5XEyDelK4JKLxeD716NiFnhzObjK4wyN8cz2ofqEi5MxwIDAQABAkAuvI9Chus8Z7nr38vq9TeHMlU50EZ6SIJArLJLJ8ZsCgHUhjnViHXvRPDkEGgulJkBueAbk6C8bOyXBhCCYpDRAiEA5wG75AWz8S1L4Z7JyKSIdZ60oak+nws6/e8yrblwcaMCIQDGqd1wPjGpxQLb7Kek3xJdfgM93IE7UBAEHdDh9ljSjQIhAM4dSvNSb1KS0vDVyD9BJwyjdZIEu34W/CTVB0fgfMa3AiBGVe+rhKmKpNDNUm1MRxo2dZ3qMf6jJEZ3XqMMzW5HJQIhALmaY6FLMKoCzM9AlmAHv3BF3B2JMPrcrtOmzql496vj";

            Label2.Text = RsaEncrypt(strData, privateKey);
        }

        public string RsaEncrypt(string rawInput, string privateKey)
        {
            if (string.IsNullOrEmpty(rawInput))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(privateKey))
            {
                throw new ArgumentException("Invalid Public Key");
            }

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                var inputBytes = Encoding.UTF8.GetBytes(rawInput);//有含义的字符串转化为字节流
                //rsaProvider.ImportParameters(privateKey);
                rsaProvider.FromXmlString(privateKey);//载入公钥
                int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
                var buffer = new byte[bufferSize];
                using (MemoryStream inputStream = new MemoryStream(inputBytes),
                     outputStream = new MemoryStream())
                {
                    while (true)
                    { //分段加密
                        int readSize = inputStream.Read(buffer, 0, bufferSize);
                        if (readSize <= 0)
                        {
                            break;
                        }

                        var temp = new byte[readSize];
                        Array.Copy(buffer, 0, temp, 0, readSize);
                        var encryptedBytes = rsaProvider.Encrypt(temp, false);
                        outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    }
                    return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
                }
            }
        }
    }
}